package job

import (
	"context"
	db2 "data_summary/common/db"
	"data_summary/common/helper"
	models "data_summary/common/models/stat"
	"data_summary/service/dao/order"
	"data_summary/service/dao/stat"
	"encoding/json"
	"fmt"
	logger "github.com/sirupsen/logrus"
	"sync"
	"time"
)

type OrderStat struct {
	TaskList []*models.StatTask
	Wg       *sync.WaitGroup
}

func NewOrderStat(wg *sync.WaitGroup) *OrderStat {
	return &OrderStat{
		Wg: wg,
	}
}

func (os *OrderStat) DoInsert(date string, companyId int) (string, error) {
	startTime := date + " 00:00:00"
	endTime := date + " 23:59:59"
	where := map[string]interface{}{"company_id": companyId, "create_time >=": startTime, "create_time <=": endTime}
	suffix := helper.SetSuffix(companyId)

	filed := "company_id,shop_id,standard_date,supplier_id,proid,cate_id," +
		"round(sum(if(num>0,num,0)),2) num," +
		"sum(if(num>0,total_receivable_amount,0)) sum_price," +
		"round(sum(if(num<0,abs(num),0)),2) refund_num," +
		"sum(if(num<0,abs(total_receivable_amount),0)) refund_sum_price," +
		" IF( business_type=\"联营\" ,sum(round((total_receivable_amount*(1-return_rate)),2)),sum(total_cost_amount)) AS sum_cost_price," +
		"IF( business_type=\"联营\" , sum(round(total_receivable_amount*return_rate,2)) ,sum(round((total_receivable_amount-total_cost_amount),2))) AS profit," +
		"round(sum(total_receivable_amount)/sum(num),2) avg_price,create_time,finish_time as update_time," +
		"TIMESTAMPDIFF(DAY,FROM_UNIXTIME(UNIX_TIMESTAMP(finish_time),\"%Y-%m-%d\"),FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),\"%Y-%m-%d\")) as day_num"
	db := db2.GetDb("order_db")
	orderDao := order.NewOrderPro(db)
	list := orderDao.TableName(suffix).GetTotal(where, filed, "company_id,shop_id,standard_date,supplier_id,cate_id,proid,day_num")
	fmt.Print(list)
	if len(list) <= 0 {
		logger.Warningln(" >>>>>>>> 暂无 销售数据 <<<<<<<<")
		return "暂无 销售数据", nil
	}
	//##进行数据查询 结束 -- 开始插入更新数据###
	stat_db := db2.GetDb("database")
	statDayOder := stat.NewStatDayOrder(stat_db)
	updateKey := []string{"num", "sum_price", "sum_cost_price", "avg_price", "profit", "refund_num", "refund_sum_price"}
	err := statDayOder.CreateTable("tj_stat_day_order_" + suffix)
	if err != nil {
		logger.Warningln(" >>>>>>>>表不存在，建表失败 <<<<<<<<", err)
		return "表不存在，建表失败", err
	}
	err = statDayOder.TableName(suffix).SetSqlExec(list, updateKey)
	if err != nil {
		fmt.Print("插入失败---", err)
		logger.Warningln(" >>>>>>>>插入失败 <<<<<<<<", err)
		return "插入失败", err
	}
	return "", nil
}

/**
*进行订单数据统计
 */

func (os *OrderStat) Run(ctx context.Context) (string, error) {
	//##进行数据查询 ###
	logger.Warningln(">>>>>>>>>>>>> Start OrderStat")
	//添加销售汇总任务
	now := time.Now()
	yesNow := now.Unix() - 86400 //昨天
	date := time.Unix(yesNow, 0).Format("2006-01-02")
	redis := db2.GetPool()
	val, err1 := redis.Get(context.Background(), "stat:task:1").Result()
	if err1 != nil {
		logger.Warningln("缓存为空", err1.Error())
	}
	fmt.Print("打印缓存", val)
	err := json.Unmarshal([]byte(val), &os.TaskList)
	if err != nil {
		logger.Warningln("解析企业json列表错误", err)
	}
	for _, v := range os.TaskList {
		_, _ = os.DoInsert(date, v.CompanyId)
	}
	return "执行完成", err
}
